package com.tigerlee.candle.activity;

import com.tigerlee.candle.R;
import com.tigerlee.candle.util.ConnectivityInformation;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

abstract public class ManagerActivity extends Activity{
	// ID of Dialog
	private static final int LODING_DIALOG = 1;
	// handle message by Handler
	private static final int TIME_OUT = 1;
	// Time out seconds to finish activity
	private static long TIMEOUT_SECS = 5 * 1000;	
	
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch(msg.what){
			case TIME_OUT:
				finishActivity(getString(R.string.toast_fail_no_connection));
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
	}
	public void startDialog(){
		// Finish if a child activity cannot connect to web for 5 secs.
		mHandler.sendMessageDelayed(mHandler.obtainMessage(TIME_OUT), TIMEOUT_SECS);
		// Show loading dialog while verifying to connect to web.
		showDialog(LODING_DIALOG);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(isConnected() == false){
			finishActivity(getString(R.string.toast_fail_no_connection));
		}
	}
	private boolean isConnected() {
		if(ConnectivityInformation.IsWifiAvailable(getApplicationContext())==true){
			return true;
		}else if(ConnectivityInformation.IsDataNetworkAvailable(getApplicationContext()) ==true){
			return true;
		}else{
			return false;
		}
		
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case LODING_DIALOG:
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage(getString(R.string.text_loading_dialog));
			dialog.setIndeterminate(true);
			// Not to accept back key
			dialog.setCancelable(false);			
			return dialog;
		default:
			break;
		}
		return super.onCreateDialog(id);
	}
	public void setOK(boolean isOK, String msg){
		if(isOK == true){
			mHandler.removeMessages(TIME_OUT);
			removeDialog(LODING_DIALOG);
		}else{
			finishActivity(msg);
		}
	}
	protected void finishActivity(String msg) {
		// TODO Auto-generated method stub
		toast(msg, Toast.LENGTH_LONG);
		finish();
	}
	public void toast(String msg, int duration){
		Toast.makeText(getApplicationContext(), msg, duration).show();
	}

}
